// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// v [author] rhyme_lph
// S [email]  rhymelph@gmail.com
// q [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/services_entity.dart';
import 'package:finance_app/src/utils/cash_utils.dart';
import 'package:finance_app/src/widgets/button/add_button.dart';
import 'package:finance_app/src/widgets/button/normal_float_text_button.dart';
import 'package:finance_app/src/widgets/button/normal_float_text_white_button.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/select/service_radio.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/dashboard/products_services/linked_services_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:flutter_sticky_header/flutter_sticky_header.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

@RouterMeta(paramName: "linkedServicesPage")
class LinkedServicesPage extends StatefulWidget {
  final List<ServicesEntity> selects;

  const LinkedServicesPage({Key key, this.selects}) : super(key: key);

  @override
  _LinkedServicesPageState createState() => _LinkedServicesPageState();
}

class _LinkedServicesPageState extends State<LinkedServicesPage>
    with PagePresenter<LinkedServicesPage, LinkedServicesProvider> {
  @override
  void initState() {
    provider.currentSelects = widget.selects;
    print('length:${widget.selects.length}');
    super.initState();
  }

  @override
  PreferredSizeWidget get appBar =>
      getDefaultAppBar(title: S.current.linked_services);

  @override
  Widget get buildEmptyWidget => Stack(
        children: [
          ColoredBox(
            color: Colors.white,
            child: Column(
              children: [
                AppSpaces.h20,
                SearchInputField(
                  controller: provider.searchController,
                  focusNode: provider.searchFocusNode,
                ),
                listBuilder<bool>(
                  selector: (_, __) =>
                      __.searchController.text.length > 0 &&
                      __.groupMap.isEmpty,
                  builder: (BuildContext context, bool value, Widget child) =>
                      NormalFormWrapper(
                    child: value == true
                        ? AddButton(
                            title:
                                '${S.current.add} "${provider.searchController.text}"',
                            onTap: () => provider.onShowAddServicesName(
                                provider.searchController.text),
                          )
                        : AddButton(
                            title: S.current.add_service,
                            onTap: provider.onShowAddServices,
                          ),
                  ),
                ),
                Expanded(
                  child: super.buildEmptyWidget,
                ),
              ],
            ),
          ),
          _buildBottomBar(),
        ],
      );

  @override
  Widget get buildWidget => Stack(
        children: [
          ColoredBox(
            color: Colors.white,
            child: Column(
              children: [
                AppSpaces.h20,
                SearchInputField(
                  controller: provider.searchController,
                  focusNode: provider.searchFocusNode,
                ),
                listBuilder<bool>(
                  selector: (_, __) =>
                      __.searchController.text.length > 0 &&
                      __.groupMap.isEmpty,
                  builder: (BuildContext context, bool value, Widget child) =>
                      NormalFormWrapper(
                    child: value == true
                        ? AddButton(
                            title:
                                '${S.current.add} "${provider.searchController.text}"',
                            onTap: () => provider.onShowAddServicesName(
                                provider.searchController.text),
                          )
                        : AddButton(
                            title: S.current.add_service,
                            onTap: provider.onShowAddServices,
                          ),
                  ),
                ),
                Expanded(
                  child: listBuilder<Map<String, List<ServicesEntity>>>(
                    selector: (_, __) =>
                        Map<String, List<ServicesEntity>>.from(__.groupMap),
                    builder: (BuildContext context,
                            Map<String, List<ServicesEntity>> value,
                            Widget child) =>
                        SmartRefresher(
                      controller: provider.refreshController,
                      onRefresh: provider.onRefresh,
                      onLoading: provider.onLoadMore,
                      enablePullUp: false,
                      child: value.entries.length == 0
                          ? super.buildEmptyWidget
                          : CustomScrollView(
                              slivers: buildSearchWidget(),
                            ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          _buildBottomBar(),
        ],
      );

  List<Widget> buildSearchWidget() {
    return provider.groupMap.entries
        .toList()
        .map((e) => buildSliver(e.key, e.value))
        .toList();
  }

  Widget buildSliver(String title, List<ServicesEntity> data) =>
      SliverStickyHeader(
        header: buildSliverHeader(title: title),
        sliver: SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, i) => buildSliverItem(data, i),
            childCount: data.length,
          ),
        ),
      );

  Widget buildSliverItem(List<ServicesEntity> data, int i) {
    return listBuilder<List<ServicesEntity>>(
        selector: (_, __) => List.from(__.currentSelects ?? []),
        builder:
            (BuildContext context, List<ServicesEntity> value, Widget child) {
          bool isSelect = value.firstWhere(
                  (element) => element.id == data[i].id,
                  orElse: () => null) !=
              null;
          return PressedOpacityButton(
            onPressed: () => provider.onSelectService(data[i]),
            padding: EdgeInsets.symmetric(
              horizontal: getDp(29),
              vertical: getDp(21),
            ),
            border: data.length == i + 1
                ? null
                : Border(
                    bottom: BorderSide(color: aceGrayColor, width: getDp(0.5))),
            color: isSelect ? aceSelectBackgroundColor : Colors.white,
            child: ServiceCheckBox(
              isSelect: isSelect,
              isSelectMode: true,
              title: data[i].name,
              isActivated: data[i].isActivated == 1,
              sellBuy:
                  '${data[i].currencyCode} ${data[i].enableSell == 0 ? '-' : CashUtils.formatCashAmount(data[i].price)} / ${data[i].enablePurchase == 0 ? '-' : CashUtils.formatCashAmount(data[i].purchasePrice)}',
            ),
          );
        });
  }

  Widget buildSliverHeader({String title}) {
    final String _title = title.isEmpty ? "*" : title;
    return ListHeaderItem(
      title: _title,
    );
  }

  Widget _buildBottomBar() => Positioned(
      bottom: getDp(32) + MediaQuery.of(context).padding.bottom,
      left: 0.0,
      right: 0.0,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          NormalFloatTextWhiteButton(
            title: S.current.cancel,
            onTap: provider.onCancel,
          ),
          SizedBox(
            width: getDp(15),
          ),
          NormalFloatTextButton(
            title: S.current.save,
            onTap: provider.onSave,
          ),
        ],
      ));
}
